package com.taa.controller;

import com.taa.entity.Product;
import com.taa.feign.ProductFeignClient;
import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/consumer")
@Slf4j
public class ConsumerController {
    private final ProductFeignClient productFeignClient;

    public ConsumerController(ProductFeignClient productFeignClient, LoadBalancerClient loadBalancerClient) {
        this.productFeignClient = productFeignClient;
    }

    @GetMapping("/products")
    @RateLimiter(name = "productRateLimiter", fallbackMethod = "rateLimiterFallback")
    @Bulkhead(name = "productBulkhead", fallbackMethod = "bulkheadFallback")
    public ResponseEntity<List<Product>> getProducts() {
        return ResponseEntity.ok(productFeignClient.getProducts());
    }

    // 限流降级方法
    public ResponseEntity<List<Product>> rateLimiterFallback(Exception ex) {
        log.warn("触发限流降级: {}", ex.getMessage());
        return ResponseEntity.status(429)
                .body(Collections.singletonList(
                        new Product(-3L, "[RateLimiter] 请求过多，请稍后重试", 0.0)
                ));
    }

    // 隔离器降级方法
    public ResponseEntity<List<Product>> bulkheadFallback(Exception ex) {
        log.warn("触发隔离器降级: {}", ex.getMessage());
        return ResponseEntity.status(429)
                .body(Collections.singletonList(
                        new Product(-1L, "[Bulkhead] 系统繁忙，请稍后重试", 0.0)
                ));
    }
}